<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';

import {
  CarOutlined,
  CreditCardOutlined,
  DollarCircleOutlined,
  ShoppingCartOutlined,
} from '@ant-design/icons-vue';
import {
  Button as AButton,
  Card as ACard,
  Descriptions as ADescriptions,
  DescriptionsItem as ADescriptionsItem,
  Divider as ADivider,
  PageHeader as APageHeader,
  Space as ASpace,
  Spin as ASpin,
  Table as ATable,
  TabPane as ATabPane,
  Tabs as ATabs,
} from 'ant-design-vue';

// TODO: 替换为真实API
import { saleOrderInfo } from '#/api/hm/saleOrder';
import { renderDict } from '#/utils/render';

// 导入子组件弹窗
import PaymentModal from './component/PaymentModal.vue';
import PickupModal from './component/PickupModal.vue';
import SaleOrderReturnModal from './component/SaleOrderReturnModal.vue';
import SaleOrderPickUpListModal from './saleOrderPickUpList-modal.vue';
import PaymentAdjustmentModal from './component/PaymentAdjustmentModal.vue';
import PaymentAdjustmentList from './component/PaymentAdjustmentList.vue';

defineOptions({ name: 'SaleOrderDetailAntd' });

const route = useRoute();
const router = useRouter();
const orderId = ref(route.params?.id as string);
const loading = ref(true);
const activeTabKey = ref('products');

// --- 弹窗状态管理 ---
const paymentModalVisible = ref(false);
const pickupModalVisible = ref(false);
const refundModalVisible = ref(false);
const paymentAdjustmentModalVisible = ref(false);

const [registerPickupModal, pickupModalApi] = useVbenModal({
  connectedComponent: SaleOrderPickUpListModal,
});

// --- 模拟数据 ---
const orderData = ref<any>({
  orderItemList: [],
  hmSaleOrderPickUpVoList: [],
  supplementaryPickupRecordList: [],
  refundRecordList: [],
  paymentRecordList: [],
  giftList: [],
});

// --- 表格列定义 ---
const productColumns = [
  {
    title: '产品名称',
    dataIndex: 'productName',
    key: 'productName',
    width: 200,
    align: 'center',
  },
  { title: '单价', dataIndex: 'price', key: 'price', align: 'right' },
  {
    title: '销售数量',
    dataIndex: 'quantity',
    key: 'quantity',
    align: 'center',
  },
  {
    title: '已提货数量',
    dataIndex: 'pickedUpQuantity',
    key: 'pickedUpQuantity',
    align: 'center',
    slots: { customRender: 'pickedUpQuantity' },
  },
  {
    title: '剩余提货量',
    dataIndex: 'remainingQuantity',
    key: 'remainingQuantity',
    align: 'center',
  },
  {
    title: '总价',
    dataIndex: 'totalAmount',
    key: 'totalAmount',
    align: 'center',
  },
];

const pickupColumns = [
  {
    title: '提货单号',
    dataIndex: 'pickUpId',
    key: 'pickUpId',
    align: 'center',
  },
  // { title: '提货类型', dataIndex: 'type', key: 'type' },
  {
    title: '提货产品',
    dataIndex: 'saleProductName',
    key: 'saleProductName',
    align: 'center',
  },
  {
    title: '提货数量',
    dataIndex: 'pickUpNum',
    key: 'pickUpNum',
    align: 'center',
  },
  // { title: '提货人', dataIndex: 'createBy', key: 'createBy' },
  {
    title: '提货时间',
    dataIndex: 'pickUpTime',
    key: 'pickUpTime',
    align: 'center',
  },
  { title: '备注', dataIndex: 'remark', key: 'remark', align: 'center' },
  // { title: '提货店铺', dataIndex: 'shopName', key: 'shopName' },
];

const supplementaryColumns = [
  {
    title: '提货单号',
    dataIndex: 'supplementaryPickupId',
    key: 'supplementaryPickupId',
    align: 'center',
  },
  {
    title: '补充提货产品',
    dataIndex: 'supplementaryProductName',
    key: 'supplementaryProductName',
    align: 'center',
  },
  {
    title: '提货数量',
    dataIndex: 'supplementaryQuantity',
    key: 'supplementaryQuantity',
    align: 'center',
  },
  // { title: '提货人', dataIndex: 'createBy', key: 'createBy' },
  {
    title: '提货时间',
    dataIndex: 'pickupTime',
    key: 'pickupTime',
    align: 'center',
  },
  // { title: '备注', dataIndex: 'remark', key: 'remark', align: 'center' },
  // { title: '提货店铺', dataIndex: 'shopName', key: 'shopName' },
];

const refundColumns = [
  {
    title: '退款单号',
    dataIndex: 'refundId',
    key: 'refundId',
    align: 'center',
  },
  // {
  //   title: '退款类型',
  //   dataIndex: 'refundType',
  //   key: 'refundType',
  //   customRender: ({ text }) => {
  //     if (text) {
  //       // 单元格内容翻译
  //       return renderDict(text, DictEnum.PAYMENT_METHOD);
  //     }
  //     return '-';
  //   },
  // },
  {
    title: '关联产品',
    dataIndex: 'saleProductName',
    key: 'saleProductName',
    align: 'center',
  },
  {
    title: '退款金额',
    dataIndex: 'refundAmount',
    key: 'refundAmount',
    align: 'center',
  },
  {
    title: '退货数量',
    dataIndex: 'returnNum',
    key: 'returnNum',
    align: 'center',
  },
  {
    title: '原因',
    dataIndex: 'reasonCode',
    key: 'reasonCode',
    customRender: ({ text }) => {
      if (text) {
        // 单元格内容翻译
        return renderDict(text, DictEnum.RETURN_REASON);
      }
      return '-';
    },
  },
  // {
  //   title: '退货状态',
  //   dataIndex: 'status',
  //   key: 'status',
  //   customRender: ({ text }) => {
  //     if (text) {
  //       return renderDict(text, DictEnum.ORDER_RERUEN_PRODUCT_STATUS);
  //     }
  //     return renderDict('0', DictEnum.ORDER_RERUEN_PRODUCT_STATUS);
  //   },
  // },
  { title: '提交时间', dataIndex: 'applyTime', key: 'applyTime' },
];

const paymentColumns = [
  {
    title: '收款单号',
    dataIndex: 'paymentNo',
    key: 'paymentNo',
    align: 'center',
  },
  { title: '收款金额', dataIndex: 'amount', key: 'amount', align: 'center' },
  {
    title: '收款方式',
    dataIndex: 'method',
    key: 'method',
    customRender: ({ text }) => {
      if (text) {
        // 单元格内容翻译
        return renderDict(text, DictEnum.PAYMENT_METHOD);
      }
      return '-';
    },
    align: 'center',
  },
  {
    title: '收款时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
  },
];

// --- 计算属性 ---
const orderStatus = computed(() => {
  const statusMap = {
    PENDING: { text: '待处理', color: 'orange' },
    PROCESSING: { text: '处理中', color: 'blue' },
    COMPLETED: { text: '已完成', color: 'green' },
    CANCELLED: { text: '已取消', color: 'red' },
  };
  return (
    statusMap[orderData.value.orderStatus] || { text: '未知', color: 'gray' }
  );
});

// 新增：将 orderData 转换为 SaleOrderReturnModal 所需的数据结构
const transformedReturnData = computed(() => {
  if (!orderData.value || !orderData.value.saleId) {
    return null;
  }
  const mainProduct = orderData.value.orderItemList?.[0] || {};
  const totalAmount = Number.parseFloat(
    String(mainProduct.totalAmount || '0').replaceAll(/[^0-9.-]+/g, ''),
  );
  const quantity = mainProduct.quantity || 0;
  const unitPrice = quantity > 0 ? totalAmount / quantity : 0;

  return {
    saleId: orderData.value.saleId,
    paidAmount: Number.parseFloat(orderData.value.returnAmount || '0'), // TODO: 确认已回款字段
    productA: {
      productId: mainProduct.productId || 'UNKNOWN_PROD_ID',
      productName: mainProduct.productName || '主产品',
      totalSold: mainProduct.quantity || 0,
      pickedQty: mainProduct.pickedUpQuantity || 0,
      unpickedQty: mainProduct.remainingQuantity || 0,
      unitPrice,
      // TODO: 以下字段需要后端在订单详情接口中提供
      alreadyReturnedPickedQty: mainProduct.alreadyReturnedPickedQty || 0,
      alreadyReturnedUnpickedQty: mainProduct.alreadyReturnedUnpickedQty || 0,
    },
    gifts:
      orderData.value.giftList?.map((gift: any) => ({
        giftId: gift.giftId || 'UNKNOWN_GIFT_ID',
        giftName: gift.giftProductName || '赠品',
        totalGiven: gift.giftNum || 0, // TODO: 确认总赠送数字段
        pickedQty: gift.giftUsedNum || 0,
        unpickedQty: (gift.giftNum || 0) - (gift.giftUsedNum || 0),
        alreadyReturnedPickedQty: gift.pickedQty || 0,
        alreadyReturnedUnpickedQty: gift.unpickedQty || 0,
      })) || [],
  };
});

// --- API & 方法 ---
async function fetchOrderDetail() {
  if (!orderId.value) return;
  loading.value = true;
  try {
    const data = await saleOrderInfo(orderId.value);
    console.log(data);
    orderData.value = data;
  } catch (error) {
    console.error('获取订单详情失败:', error);
  } finally {
    loading.value = false;
  }
}

function goBack() {
  router.push('/saleOrder');
}

function openPaymentModal() {
  paymentModalVisible.value = true;
}

function openNewPickupModal() {
  pickupModalVisible.value = true;
}

function openRefundModal() {
  refundModalVisible.value = true;
}

function openPaymentAdjustmentModal() {
  paymentAdjustmentModalVisible.value = true;
}

function openPickupHistoryModal(record: any) {
  if (!record?.productId) return;
  pickupModalApi.setData({
    productId: record.productId,
    pickUpType: 'pickUpNumHis',
    saleOrderId: orderData.value.saleId,
  });
  pickupModalApi.open();
}

function handleSuccess() {
  fetchOrderDetail();
}

onMounted(() => {
  fetchOrderDetail();
});
</script>

<template>
  <div class="bg-gray-100 p-4">
    <ASpin :spinning="loading">
      <APageHeader
        title="订单详情"
        @back="goBack"
        class="mb-4 rounded bg-white"
      >
        <template #extra>
          <ASpace>
            <!--            <AButton>打印订单</AButton>-->
            <AButton @click="openPaymentModal">收款</AButton>
            <AButton type="primary" @click="openNewPickupModal"> 提货 </AButton>
            <AButton @click="openPaymentAdjustmentModal">申请回款调整</AButton>
            <AButton danger @click="openRefundModal">退款</AButton>
          </ASpace>
        </template>
      </APageHeader>

      <ACard :bordered="false" class="mb-4">
        <ADescriptions :column="3" bordered>
          <ADescriptionsItem label="订单号">
            {{ orderData.orderNo }}
          </ADescriptionsItem>
          <ADescriptionsItem label="客户姓名">
            {{ orderData.customerName }}
          </ADescriptionsItem>
          <ADescriptionsItem label="客户电话">
            {{ orderData.customerPhone }}
          </ADescriptionsItem>
          <!--          <ADescriptionsItem label="订单状态">-->
          <!--            <ATag :color="orderStatus.color">{{ orderStatus.text }}</ATag>-->
          <!--          </ADescriptionsItem>-->
          <ADescriptionsItem label="订单总额">
            {{ orderData.saleAmount }}
          </ADescriptionsItem>
          <ADescriptionsItem label="下单时间">
            {{ orderData.createTime }}
          </ADescriptionsItem>
        </ADescriptions>
      </ACard>

      <ACard :bordered="false">
        <ATabs v-model:active-key="activeTabKey">
          <ATabPane key="products">
            <template #tab>
              <span><ShoppingCartOutlined /> 订单明细</span>
            </template>
            <ATable
              :columns="productColumns"
              :data-source="orderData.orderItemList"
              :pagination="false"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'pickedUpQuantity'">
                  <a @click="openPickupHistoryModal(record)">{{
                    record.pickedUpQuantity
                  }}</a>
                </template>
              </template>
            </ATable>
          </ATabPane>

          <ATabPane key="pickups">
            <template #tab>
              <span><CarOutlined /> 提货</span>
            </template>
            <h3 class="mb-4">正常提货记录</h3>
            <ATable
              :columns="pickupColumns"
              :data-source="orderData.hmSaleOrderPickUpVoList"
              :pagination="false"
              row-key="id"
              class="mb-4"
            />
            <ADivider />
            <h3 class="mb-4 mt-4">补充提货记录</h3>
            <ATable
              :columns="supplementaryColumns"
              :data-source="orderData.supplementaryPickupRecordList"
              :pagination="false"
              row-key="id"
            />
          </ATabPane>

          <ATabPane key="payments">
            <template #tab>
              <span><CreditCardOutlined /> 收款记录</span>
            </template>
            <ATable
              :columns="paymentColumns"
              :data-source="orderData.paymentRecordList"
              :pagination="false"
              row-key="id"
            />
          </ATabPane>

          <ATabPane key="refunds">
            <template #tab>
              <span><DollarCircleOutlined /> 退款与退货</span>
            </template>
            <ATable
              :columns="refundColumns"
              :data-source="orderData.refundRecordList"
              :pagination="false"
              row-key="id"
            />
          </ATabPane>

          <ATabPane key="adjustments">
            <template #tab>
              <span><DollarCircleOutlined /> 回款调整</span>
            </template>
            <PaymentAdjustmentList
              v-if="activeTabKey === 'adjustments'"
              :sale-id="orderId"
              @refresh="handleSuccess"
            />
          </ATabPane>

          <!-- <ATabPane key="logs">
            <template #tab>
              <span><SolutionOutlined /> 操作日志</span>
            </template>
            <p>此处显示订单相关的操作日志。</p>
          </ATabPane> -->
        </ATabs>
      </ACard>
    </ASpin>

    <!-- 弹窗组件 -->
    <PaymentModal
      v-model:visible="paymentModalVisible"
      :order-id="orderId"
      :order-data="orderData"
      @success="handleSuccess"
    />
    <PickupModal
      v-model:visible="pickupModalVisible"
      :order-id="orderId"
      :order-data="orderData"
      @success="handleSuccess"
    />
    <!-- 修改：将转换后的数据传递给退款弹窗 -->
    <SaleOrderReturnModal
      v-model:visible="refundModalVisible"
      :order-data-input="transformedReturnData"
      @success="handleSuccess"
    />
    <PaymentAdjustmentModal
      v-model:visible="paymentAdjustmentModalVisible"
      :order-data="orderData"
      @success="handleSuccess"
    />
    <SaleOrderPickUpListModal
      @register="registerPickupModal"
      @success="handleSuccess"
    />
  </div>
</template>

<style scoped>
.p-4 {
  padding: 16px;
}

.bg-gray-100 {
  background-color: #f0f2f5;
}

.bg-white {
  background-color: #fff;
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
  color: rgb(0 0 0 / 65%);
}
</style>
